package com.dreamer.service.lottery.impl;

import com.dreamer.domain.lottery.Lottery;
import com.dreamer.domain.lottery.Player;
import com.dreamer.repository.lottery.LotteryDao;
import com.dreamer.repository.lottery.PlayerDao;
import com.dreamer.service.lottery.LotteryHandler;
import com.dreamer.service.lottery.PlayerHandler;
import com.dreamer.service.mobile.impl.BaseHandlerImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ps.mx.otter.exception.ApplicationException;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class LotteryHandlerImpl extends BaseHandlerImpl<Lottery> implements LotteryHandler {

    @Autowired
    private PlayerDao playerDao;


    /**
     * 获取抽奖次数
     *
     * @param uid
     * @param lid
     * @return
     */
    @Override
    public Integer getLotteryCount(Integer uid, Integer lid) {
        List<Player> players = playerDao.findByLidAndUid(uid, lid);
        if (players == null || players.isEmpty()) {
            return 0;
        }
        //满足抽奖条件的与没有抽过的
        players = players.stream().filter(player -> player.getOpen() && !player.getGived()).collect(Collectors.toList());
        return players.size();
    }

    /**
     * 获取抽奖
     *
     * @param uid 抽奖人
     * @param lid 参与的活动
     * @return
     */
    @Override
    @Transactional
    public Player getGift(Integer uid, Integer lid) {
        //找出是否有有参与抽奖
        Player player = playerDao.findByLidAndUidNotGived(uid, lid);
        if (player == null) {
            throw new ApplicationException("抱歉,您没有抽奖次数了!");
        }
        //设置成抽过了
        player.setGived(true);
        player = playerDao.merge(player);
        return player;
    }

    /**
     * 获取所有抽过的奖的结果
     *
     * @param uid
     * @param lid
     * @return
     */
    @Override
    public List<Player> getGiftResults(Integer uid, Integer lid) {
        List<Player> players = playerDao.findByLidAndUid(uid, lid);
        players = players.stream().filter(player -> player.getGived()).collect(Collectors.toList());
        return players;
    }
}
